package com.fone.player.online.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.RstSerializer;
import com.fone.player.client.SearchRst;
import com.fone.player.client.SpecllistRst;
import com.fone.player.client.SpecllistRst.Cnt;
import com.fone.player.entity.HorizontalInfo;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.entity.SearchInfo;
import com.fone.player.online.adapter.GridModeAdapter;
import com.fone.player.online.fragment.GridModeFragment;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SharedPreferenceOnline;
import com.fone.player.view.FilmSetSearch;
import com.fone.player.view.FilmSetSearch.OnSearcherListener;
import com.fone.player.view.ReGridView;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

/**
 * GridView模版的activity，包括横版和竖版
 */
public class GridModeActivity extends BaseActivity implements IXListViewListener {
	/** 日志标签 */
	private static final String TAG = "HorizontalActivity";

	private ImageView tagView;
	private Button mLeftBt;
	private Button mRightBt;
	private TextView mTitleTv;
	private XListView mListView;
	private FilmSetSearch filmSearch;
	private GridModeAdapter adapter;

	private RstSerializer rstSerializer;
	private SharedPreferenceOnline sp;

	private String url;
	private String name;
	private String id;

	private String webUrl;

	private String shost;
	private String host;
	private String clid;
	private String nurl;

	private String category;
	private String country;
	private String year;

	private int page = 1;
	private int webHight;

	private List<HorizontalInfo> horizontalList = new ArrayList<HorizontalInfo>();

	private static final int SUCCESS = 0;
	private static final int FAILURE = 1;

	// 是否第一次加载
	private boolean isFirst = true;
	// 是否为栏目数据
	private boolean isColumn = true;
	// 是否为固定url，即来自于Intent传递的url;
	private boolean isFix = true;

	private SpecllistRst t;
	/** 显示类型：11是横版显示,10是竖版显示 */
	private int showtype;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_horizontal);

		getIntentData();
		initView();

		initData();
	}

	/**
	 * 获得Intent传递值
	 */
	private void getIntentData() {
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		name = intent.getStringExtra("name");
		id = intent.getStringExtra("id");
		showtype = intent.getIntExtra("showtype", 11);
	}

	/**
	 * 布局控件初始化
	 */
	private void initView() {
		// 标题栏
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_left_title_tv);

		mLeftBt.setOnClickListener(new BtnOnClicker());
		mRightBt.setVisibility(View.GONE);
		mTitleTv.setVisibility(View.VISIBLE);
		mTitleTv.setText(name);

		// ListView
		mListView = (XListView) findViewById(R.horizontal.list);

		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(true);
		mListView.setEnableDragLoadMore(false);
		mListView.setXListViewListener(this);
		// mListView.setOnScrollListener(this);

		// 分类检索线
		tagView = (ImageView) findViewById(R.horizontal.tagview);
		filmSearch = (FilmSetSearch) findViewById(R.horizontal.film_search);
		filmSearch.setOnSearcherListener(new SearchListener());
	}

	private void initData() {
		rstSerializer = new RstSerializer();
		sp = new SharedPreferenceOnline(GridModeActivity.this, id);

		String data = sp.getData();
		// 当缓存为空时，向服务器申请数据
		if (TextUtils.isEmpty(data)) {
			initColumnData(url);
		} else {
			try {
				t = (SpecllistRst) rstSerializer.fromString(SpecllistRst.class, data);
				updateHorizontal(true, t);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				initColumnData(url);
			}
			// 当有网且缓存数据超时，重新申请数据
			if (FoneUtil.isNetOk(GridModeActivity.this) && isTimeOut(sp.getTime(), System.currentTimeMillis())) {
				t = null;
				initColumnData(url);
			}
		}
	}

	/**
	 * 判断缓存是否过期
	 */
	private boolean isTimeOut(Long sptime, Long currenttime) {
		long num = (long) ((currenttime - sptime) / 60000);
		return num > 15;
	}

	/**
	 * 申请栏目数据
	 */
	private boolean initColumnData(String path) {

		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(GridModeActivity.this)) {
			Request.getInstance().specllist(FoneUtil.onlineUrl(path), new HorizontalCallBack());
			L.v(TAG, "initColumnData", FoneUtil.onlineUrl(path));
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 申请搜索数据
	 */
	private boolean initSearchData(int page) {
		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(GridModeActivity.this)) {
			SearchInfo info = new SearchInfo();
			info.columnid = clid;
			info.typename = category;
			info.area = country;
			info.year = year;
			Request.getSearchInstance(GridModeActivity.this).search(4, "", page, "0", "0", "0", info, new SearchCallBack());
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 栏目数据返回处理
	 */
	private class HorizontalCallBack implements Callback<SpecllistRst> {

		@Override
		public void onSuccess(SpecllistRst t) {
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			updateHorizontal(false, t);
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "HorizontalCallBack", "-onFailure-" + error.toString());
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}

	}

	/**
	 * 搜索数据返回处理
	 */
	private class SearchCallBack implements Callback<SearchRst> {

		@Override
		public void onSuccess(SearchRst t) {
			// TODO Auto-generated method stub
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			L.v(TAG, "SearchCallBack", "-onSuccess-" + t.result);

			if (t.result == SUCCESS) {
				if (isFirst) {
					horizontalList.clear();
				}
				frashSearchListView(t);
				loadNextPage(t);
				isFirst = false;
				
			} else {
				// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
				mListView.setPullRefreshEnable(false);
				mListView.setEnableDragLoadMore(false);
				mListView.setPullRefreshEnable(true);
			}
		}

		@Override
		public void onFailure(Error error) {
			// TODO Auto-generated method stub
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			L.v(TAG, "SearchCallBack", "-onFailure-" + error.toString());
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}

	}

	private void updateHorizontal(boolean isLocal, SpecllistRst t) {
		L.v(TAG, "HorizontalCallBack", "-onSuccess-" + t.result);

		if (t.result == SUCCESS) {
			if(GridModeActivity.this.t == null){
				GridModeActivity.this.t = t;
			}
			if (isFirst) {

				if (!isLocal && isFix) {
					sp.setAll(System.currentTimeMillis(), rstSerializer.toString(t));
				}

				horizontalList.clear();
				initSearch(t);
				getServerData(t);
			}

			frashColumnListView(t);
			loadNextPage(t);
			isFirst = false;

		} else {
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}
	}

	/**
	 * 初始化"分类检索"
	 */
	private void initSearch(SpecllistRst t) {
		// TODO Auto-generated method stub
//		/** 判断"分类检索"是否显示 */
//		if (t.label != null && t.label.isshow != null && t.label.isshow.equals("1")) {
//
//			/** 判断"分类检索"是否有栏目数据 */
//			if (t.cols != null && t.cols.colList != null && !t.cols.colList.isEmpty()) {
//				// t.cols.colList
//				L.v(TAG, "update", "-size-" + t.cols.colList.size());
//				filmSearch.initColumn(t.cols.colList);
//			}
//
//			/** 判断"分类检索"是否有检索数据 */
//			if (t.label.lbs != null && !t.label.lbs.isEmpty()) {
//				filmSearch.initSearch(t.label.lbs);
//			}
//
//			tagView.setVisibility(View.VISIBLE);
//			filmSearch.setVisibility(View.VISIBLE);
//		}
		
		/** 判断"分类检索"是否显示 */
		if (t.label != null && t.label.isshow != null && t.label.isshow.equals("1")) {

			/** 判断"分类检索"是否有检索数据 */
			if (t.label.lbs != null && !t.label.lbs.isEmpty()) {
				filmSearch.initSearch(t.label.lbs);
				tagView.setVisibility(View.VISIBLE);
				filmSearch.setVisibility(View.VISIBLE);
			}

		}
		
		/** 判断"分类检索"是否有栏目数据 */
		if (t.cols != null && t.cols.colList != null && !t.cols.colList.isEmpty()) {
			filmSearch.initColumn(t.cols.colList);
			tagView.setVisibility(View.VISIBLE);
			filmSearch.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 初始化服务器返回参数
	 */
	private void getServerData(SpecllistRst t) {
		// TODO Auto-generated method stub
		if (t.shost != null) {
			shost = t.shost;
			L.v(TAG, "initServerInfo", "-shost-" + shost);
		}

		if (t.host != null) {
			host = t.host;
			L.v(TAG, "initServerInfo", "-host-" + host);
		}

		if (t.label != null && t.label.clid != null) {
			clid = t.label.clid;
			L.v(TAG, "initServerInfo", "-clid-" + clid);
		}

	}

	/**
	 * 刷新"列表"数据
	 */
	private void frashColumnListView(SpecllistRst t) {
		// TODO Auto-generated method stub
		if (t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()) {

			for (Cnt cnt : t.cnts.cntList) {
				HorizontalInfo info = new HorizontalInfo();
				info.name = cnt.name;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;
				info.btnply = cnt.btnply;
				info.weibourl = cnt.weibourl;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.quality = cnt.quality;
				info.updatedetail = cnt.updatedetail;
				info.ftv = cnt.ftv;

				horizontalList.add(info);
			}
			if(adapter == null){
				adapter = new GridModeAdapter(GridModeActivity.this, GridModeActivity.this.t, horizontalList, showtype);
				mListView.setAdapter(adapter);
			}else {
				adapter.setData(GridModeActivity.this.t,horizontalList);
			}
		}
	}

	/**
	 * 刷新"搜索"数据
	 */
	private void frashSearchListView(SearchRst t) {
		// TODO Auto-generated method stub
		if (t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()) {
			for (com.fone.player.client.SearchRst.Cnt cnt : t.cnts.cntList) {
				HorizontalInfo info = new HorizontalInfo();
				info.name = cnt.name;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;

				info.quality = cnt.score;
				// info.updatedetail = cnt.updatedetail;

				horizontalList.add(info);
			}
			if(adapter == null){
				adapter = new GridModeAdapter(GridModeActivity.this, GridModeActivity.this.t, horizontalList, showtype);
				mListView.setAdapter(adapter);
			}else {
				if (category.equals(getString(R.string.all)) && country.equals(getString(R.string.all)) && year.equals(getString(R.string.all))) {
					adapter.setData(GridModeActivity.this.t, horizontalList);
				} else {
					adapter.setData(null, horizontalList);
				}
			}
		}

	}

	/**
	 * 分类检索点击响应
	 */
	private class SearchListener implements OnSearcherListener {

		@Override
		public void onClick(String category, String country, String year, String attention) {

			L.v(TAG, "initFileSearch", "HorizontalActivity- category -" + category + "- country -" + country + "- year -" + year + "- attention -" + attention + "- clid -" + clid);

			// 点击搜索
			if (TextUtils.isEmpty(attention)) {

				setSearchData(category, country, year);
				page = 1;
				initSearchData(page);
				isColumn = false;
			}
			// 点击栏目
			else {
				url = attention;
				initColumnData(url);
				isColumn = true;
			}
			isFirst = true;
			isFix = false;
		}

	}

	private void setSearchData(String category, String country, String year) {
		// TODO Auto-generated method stub
		this.category = category;
		this.country = country;
		this.year = year;
	}

	/** "搜索"是否存在下一页 . */
	private void loadNextPage(SearchRst t) {
		// TODO Auto-generated method stub
		if (t.rp != null && t.rp.m >= t.rp.p) {
			page = t.rp.p;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		} else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}

	/** "栏目"是否存在下一页 . */
	private void loadNextPage(SpecllistRst t) {
		// TODO Auto-generated method stub
		if (t.rp != null && t.rp.m == 1 && t.rp.nurl != null) {
			nurl = t.rp.nurl;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		} else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}

	/**
	 * 列表中item监听
	 */
	private class HorizontalItemClicker implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 判断网络状态
			if (FoneUtil.isNetOk(GridModeActivity.this)) {
				HorizontalInfo info = (HorizontalInfo) adapter.getItem(position);
				L.v(TAG, "HorizontalItemClicker", info.name);
				Activity2poster.startActivity(GridModeActivity.this, getRedirectInfo(info));
			}

		}
	}

	private RedirectInfo getRedirectInfo(HorizontalInfo info) {
		RedirectInfo redirectInfo = new RedirectInfo();
		redirectInfo.host = host;
		redirectInfo.utp = info.utp;
		redirectInfo.weibourl = info.weibourl;
		redirectInfo.url = info.url;
		redirectInfo.vgurl = info.url;
		redirectInfo.xyzplayurl = info.url;
		redirectInfo.dnfs = info.dfnt;
		redirectInfo.name = info.name;
		redirectInfo.ourl = info.ourl;
		redirectInfo.btnply = info.btnply;
		redirectInfo.pic = info.pic2;
		return redirectInfo;
	}

	@Override
	public void onRefresh() {
		// TODO 下拉刷新
		page = 1;
		mListView.onLoad();
		// 如果"栏目"下拉刷新
		if (isColumn && initColumnData(url)) {
			isFirst = true;
		}
		// 如果"搜索"下拉刷新
		else if (!isColumn && initSearchData(page)) {
			isFirst = true;
		}
	}

	@Override
	public void onLoadMore() {
		// TODO 上拉更多
		// 如果"栏目"下拉刷新
		if (isColumn) {
			initColumnData(nurl);
		}
		// 如果"搜索"下拉刷新
		else if (!isColumn) {
			L.v(TAG, "onLoadMore", "-page:-" + page);
			initSearchData(page);
		}
	}

	private class BtnOnClicker implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.common_title_left_bt:
				finish();
				break;

			default:
				break;
			}
		}

	}

	private class newsAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 1;

		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;

		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = LayoutInflater.from(GridModeActivity.this).inflate(R.layout.view_grid_horizontal, parent, false);

			ReGridView grid = (ReGridView) v.findViewById(R.horizontal.grid);
			// 可将行间隔及列间隔常量化
			grid.setAdapter(adapter);
			grid.setOnItemClickListener(new HorizontalItemClicker());
			return v;

		}
	}
}
